package com.company.planner.service;

import com.company.planner.entity.*;
import com.haulmont.cuba.core.Persistence;
import com.haulmont.cuba.core.Transaction;
import com.haulmont.cuba.core.TransactionalDataManager;
import com.haulmont.cuba.core.global.DataManager;
import com.haulmont.cuba.core.global.Metadata;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.List;

@Service(WordsService.NAME)
public class WordsServiceBean implements WordsService {

    @Inject
    private Logger log;
    @Inject
    private Metadata metadata;
    @Inject
    private Persistence persistence;
    @Inject
    private TransactionalDataManager transactionalDataManager;
    @Inject
    private DataManager dataManager;

    @Override
    public void batchOperationRecord(List<HotWords> hotWords, Integer switchEnum) {
        try (Transaction tx = persistence.createTransaction()) {
            hotWords.forEach(words -> {
                HotOperationRecord record = metadata.create(HotOperationRecord.class);
                record.setNodeState(NodeState.BEGIN);
                if (switchEnum.equals(SwitchEnum.OFF.getId())) {
                    record.setOperationState(OperationState.DELETED);
                } else {
                    record.setOperationState(OperationState.INSERT);
                }
                record.setWord(words);
                record.setWords(words.getWord());
                transactionalDataManager.save(record);
            });
            tx.commit();
        } catch (Exception e) {
            log.error("Error", e);
        }

    }

    @Override
    public void batchDelHotWords(List<HotWords> hotWords) {
        try (Transaction tx = persistence.createTransaction()) {
            hotWords.forEach(words -> {
                transactionalDataManager.remove(words);
            });
            tx.commit();
        } catch (Exception e) {
            log.error("Error", e);
        }
    }

    @Override
    public List<HotOperationRecord> getHotOperationRecords(String words) {
        return dataManager.load(HotOperationRecord.class)
                .query("select e from planner_HotOperationRecord e where e.words = :words and e.nodeState = 0 and e.operationState = 'edit'")
                .parameter("words", words)
                .list();
    }

    @Override
    public boolean existWordsOperationRecords(HotWords hotWords) {
        List<HotOperationRecord> operationRecords = dataManager.load(HotOperationRecord.class)
                .query("select e from planner_HotOperationRecord e where e.word = :word and e.nodeState = 0 and e.operationState = 'edit'")
                .parameter("word", hotWords)
                .list();
        return operationRecords.isEmpty();
    }

}